package vn.keho.module.dompeto.fragment;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bingkaimedia.merchantbeta.R;
import com.mobeta.android.dslv.DragSortController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import vn.keho.define.convert.DateUtil;
import vn.keho.module.dompeto.HomeActivity;
import vn.keho.module.dompeto.model.ChannelModel;
import vn.keho.module.dompeto.model.PageModel;
import vn.keho.module.dompeto.rest.DompetoRequest;
import vn.keho.module.dompeto.sqlite.DompetoSqliteHelper;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * to handle interaction events.
 * Use the {link vn.keho.module.dompeto.fragment.LeftFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MainFragment extends Fragment {
    public static final int MAIN_FRAGMENT_ID = 0;

    private ViewPager viewPager;
    private WalletPageFragmentAdapter walletPageFragmentAdapter;

    private Button btnPrevious, btnNext;
    private ImageView imgDragDrop;



    public RelativeLayout frmFragmentController;

    private TextView txtPageTitle;

    public boolean isEditMode = false;
    private long changePageFragmentAt = 0;
    private int startDragPage = 0;

    private DompetoSqliteHelper dompetoSqliteHelper;

    private List<PageModel> listPageModel = new ArrayList<PageModel>();

    // TODO: Rename and change types and number of parameters
    public static MainFragment newInstance() {
        MainFragment fragment = new MainFragment();

        return fragment;
    }

    public MainFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dompetoSqliteHelper = new DompetoSqliteHelper(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_main, container, false);

        txtPageTitle = (TextView) view.findViewById(R.id.txtPageTitle);

        walletPageFragmentAdapter = new WalletPageFragmentAdapter(getActivity().getSupportFragmentManager());

        Log.i("Main Fragment", "On Create View");
        viewPager = (ViewPager) view.findViewById(R.id.viewPager);
        viewPager.setAdapter(walletPageFragmentAdapter);
        viewPager.setOnPageChangeListener(onPageChangeListener);
        viewPager.setOffscreenPageLimit(100);


        imgDragDrop = (ImageView) view.findViewById(R.id.imgDragDrop);


        frmFragmentController = (RelativeLayout) view.findViewById(R.id.frmFragmentController);

        btnPrevious = (Button) view.findViewById(R.id.btnPrevious);
        btnPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentPage = viewPager.getCurrentItem();
                int nextPage = currentPage - 1;
                viewPager.setCurrentItem(nextPage);
            }
        });
        btnNext = (Button) view.findViewById(R.id.btnNext);
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int currentPage = viewPager.getCurrentItem();
                int nextPage = currentPage + 1;
                viewPager.setCurrentItem(nextPage);
            }
        });

        reloadData(listPageModel);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

    }

    @Override
    public void onDetach() {
        super.onDetach();

    }

    /**
     * For ViewPager Fragment
     */
    private class WalletPageFragmentAdapter extends FragmentPagerAdapter {
        private int pageCount = 0;
        private List<PageModel> pageData = new ArrayList<PageModel>();
        private Map<Integer, PageFragment> mapPageFragment = new HashMap<Integer, PageFragment>();

        public WalletPageFragmentAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            PageFragment pageFragment = PageFragment.newInstance(i, pageData.get(i).getSlots());
            mapPageFragment.put(i, pageFragment);
            return pageFragment;
        }

        public PageFragment getPageFragment(int i) {
            return mapPageFragment.get(i);
        }

        @Override
        public int getCount() {
            return pageCount;
        }

        @Override
        public int getItemPosition(Object object) {
            PageFragment pageFragment = (PageFragment) object;
            if (pageFragment != null) {
                pageFragment.updateEditMode();
            }
            return super.getItemPosition(object);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            String title = pageData.get(position).getTitle();
            return title;
        }

        public void setPageCount(List<PageModel> pageData) {
            this.pageData = pageData;
            this.pageCount = pageData.size();
            notifyDataSetChanged();
        }
    }

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
        }

        @Override
        public void onPageSelected(int i) {
            updateHeaderAction();
        }

        @Override
        public void onPageScrollStateChanged(int i) {
        }
    };

    private void updateHeaderAction() {
        int currentPage = viewPager.getCurrentItem();
        if (currentPage == 0) {
            btnPrevious.setVisibility(View.INVISIBLE);
        } else {
            btnPrevious.setVisibility(View.VISIBLE);
        }

        if (currentPage >= walletPageFragmentAdapter.getCount() - 1) {
            btnNext.setVisibility(View.INVISIBLE);
        } else {
            btnNext.setVisibility(View.VISIBLE);
        }

        if(currentPage >= 0 && currentPage < walletPageFragmentAdapter.getCount()) {
            String title = walletPageFragmentAdapter.getPageTitle(currentPage).toString();
            txtPageTitle.setText(title);
        }
    }

    public void onChangePageFragment(int leftRightPosition, int removeIndex) {

        long currentTime = DateUtil.currentTimeStamp();
        int currentPage = viewPager.getCurrentItem();
        int reducePosition = leftRightPosition - (currentPage - startDragPage) * frmFragmentController.getWidth();

        if (Math.abs(reducePosition) > frmFragmentController.getWidth() / 3 && currentTime > changePageFragmentAt + 3000) {

            if (reducePosition < 0 && currentPage > 0) {
                int nextPage = currentPage - 1;
                viewPager.setCurrentItem(nextPage);
                changePageFragmentAt = currentTime;


            } else if (reducePosition > 0 && currentPage < walletPageFragmentAdapter.getCount() - 1) {
                int nextPage = currentPage + 1;
                viewPager.setCurrentItem(nextPage);
                changePageFragmentAt = currentTime;
            }
        }
    }

    public void createDragImage(Bitmap bitmap, Point position) {
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(bitmap.getWidth(), bitmap.getHeight());
        lp.leftMargin = position.x;
        lp.topMargin = position.y;
        imgDragDrop.setLayoutParams(lp);
        imgDragDrop.setImageBitmap(bitmap);
        startDragPage = viewPager.getCurrentItem();
    }

    public void showDragImage() {
        imgDragDrop.setVisibility(View.VISIBLE);
    }

    public void updateDragImage(Point position) {
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) imgDragDrop.getLayoutParams();
        lp.leftMargin = position.x - (viewPager.getCurrentItem() - startDragPage) * frmFragmentController.getWidth();
        lp.topMargin = position.y;
        imgDragDrop.setLayoutParams(lp);

        showDragImage();
    }

    public void dropDragImage() {
        imgDragDrop.setImageDrawable(null);
        imgDragDrop.setVisibility(View.GONE);
    }

    public void changeEditMode(int removeMode) {
        if (removeMode == DragSortController.CLICK_REMOVE) {
            isEditMode = true;
        } else {
            isEditMode = false;
        }
        //Apply all page fragment
        walletPageFragmentAdapter.notifyDataSetChanged();
    }

    public void reloadData(List<PageModel> listPageModel) {
        this.listPageModel = listPageModel;
        if(viewPager != null) {
            walletPageFragmentAdapter.setPageCount(listPageModel);
            updateHeaderAction();
        }
    }

    public void changeChannelPage(int removeIndex) {
        int currentPage = viewPager.getCurrentItem();
        if(startDragPage != currentPage) {
            PageFragment pageFragment = walletPageFragmentAdapter.getPageFragment(currentPage);
            int validIndex = pageFragment.findSlotAvailable(imgDragDrop);
            if(validIndex != AdapterView.INVALID_POSITION) {
                PageFragment removePageFragment = walletPageFragmentAdapter.getPageFragment(startDragPage);
                ChannelModel channelModel = removePageFragment.removeChannel(removeIndex);
                pageFragment.addChannel(channelModel, validIndex);

                /*HomeActivity homeActivity = (HomeActivity) getActivity();
                homeActivity.onSyncWithServer();*/
            }
        }
    }

    public int findPositionImageDrop() {
        int currentPage = viewPager.getCurrentItem();
        PageFragment pageFragment = walletPageFragmentAdapter.getPageFragment(currentPage);
        int validIndex = pageFragment.findSlotAvailable(imgDragDrop);
        return validIndex;
    }

    public void moveBlackBox(int removeIndex) {
        int currentPage = viewPager.getCurrentItem();
        PageFragment pageFragment = walletPageFragmentAdapter.getPageFragment(currentPage);
        ChannelModel channelModel = pageFragment.findChannelIndex(removeIndex);

        //Insert database
        dompetoSqliteHelper.insertChannel(DompetoRequest.username, channelModel);

        /*HomeActivity homeActivity = (HomeActivity) getActivity();
        homeActivity.onSyncWithServer();*/
    }

    public void clearBlackBox(ChannelModel channelModel) {
        int currentPage = viewPager.getCurrentItem();
        PageFragment pageFragment = walletPageFragmentAdapter.getPageFragment(currentPage);
        pageFragment.clearChannel(channelModel.getSlotid() - 1);

        HomeActivity homeActivity = (HomeActivity) getActivity();
        homeActivity.onSyncWithServer();
    }

    public void restoreBlackBox(ChannelModel channelModel, int addIndex) {
        int currentPage = viewPager.getCurrentItem();
        PageFragment pageFragment = walletPageFragmentAdapter.getPageFragment(currentPage);
        pageFragment.addChannel(channelModel, addIndex);
        channelModel.setSlotid(addIndex + 1);

        HomeActivity homeActivity = (HomeActivity) getActivity();
        homeActivity.onSyncWithServer();
    }

    public int findEmptySlot() {
        int currentPage = viewPager.getCurrentItem();
        if(currentPage >= 0) {
            PageFragment pageFragment = walletPageFragmentAdapter.getPageFragment(currentPage);
            return pageFragment.findEmptySlot();
        }
        return AdapterView.INVALID_POSITION;
    }
}
